<template>
  <div class="toolbar">
    <div class="toolbar-left">
      <div class="toolbar-group">
        <FileNameInput
          :model-value="fileName"
          @update:modelValue="$emit('update:fileName', $event)"
        />
        <ThemeSelect :model-value="selectedTheme" @update:modelValue="handleThemeChange" />

        <LanguageSelect :model-value="selectedLanguage" @update:modelValue="handleLanguageChange" />
      </div>

      <div class="toolbar-group">
        <NumberStepper
          :model-value="parseInt(selectedFontSize)"
          @update:modelValue="handleFontSizeChange"
        />

        <FontFamilySelect
          :model-value="selectedFontFamily"
          @update:modelValue="handleFontFamilyChange"
        />

        <ColorPicker :model-value="selectedColor" @update:modelValue="handleColorUpdate" />

        <PaddingStepper :model-value="paddingY" @update:modelValue="handlePaddingYChange" />
      </div>
    </div>

    <div class="toolbar-right">
      <div class="toolbar-group action-buttons">
        <button
          class="toolbar-button"
          @click="handleFormat"
          :disabled="isFormatting"
          title="格式化代码"
        >
          <span class="button-icon">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="14"
              height="14"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <line x1="21" y1="10" x2="3" y2="10"></line>
              <line x1="21" y1="6" x2="3" y2="6"></line>
              <line x1="21" y1="14" x2="3" y2="14"></line>
              <line x1="21" y1="18" x2="3" y2="18"></line>
            </svg>
          </span>
          <span class="button-text">{{ isFormatting ? '格式化中...' : '格式化' }}</span>
        </button>
        <button class="toolbar-button" @click="handleCopy" title="复制代码到剪贴板">
          <span class="button-icon">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="14"
              height="14"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
              <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
            </svg>
          </span>
          <span class="button-text">复制</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType } from 'vue'
import type { ThemeType } from './ThemeConfig'
import type { LanguageType } from './LanguageConfig'
import html2canvas from 'html2canvas'

// 导入重构的组件
import FileNameInput from '../common/input/FileNameInput.vue'
import ThemeSelect from '../common/select/ThemeSelect.vue'
import LanguageSelect from '../common/select/LanguageSelect.vue'
import NumberStepper from '../common/stepper/NumberStepper.vue'
import FontFamilySelect from '../common/select/FontFamilySelect.vue'
import ColorPicker from '../common/picker/ColorPicker.vue'
import PaddingStepper from '../common/stepper/PaddingStepper.vue'

export default defineComponent({
  name: 'CodeMirrorToolbar',
  components: {
    FileNameInput,
    ThemeSelect,
    LanguageSelect,
    NumberStepper,
    FontFamilySelect,
    ColorPicker,
    PaddingStepper,
  },
  props: {
    theme: {
      type: String as PropType<ThemeType>,
      required: true,
    },
    language: {
      type: String as PropType<LanguageType>,
      required: true,
    },
    isFormatting: {
      type: Boolean,
      default: false,
    },
    backgroundColor: {
      type: String,
      default: '#1a1a1a',
    },
    fontSize: {
      type: Number,
      default: 14,
    },
    fontFamily: {
      type: String,
      default: "'Menlo', Monaco, Consolas, monospace",
    },
    padding: {
      type: Object as PropType<{ x: number; y: number }>,
      default: () => ({ x: 32, y: 40 }),
    },
    fileName: {
      type: String,
      default: 'untitled.txt',
    },
  },
  emits: [
    'update:theme',
    'update:language',
    'update:backgroundColor',
    'update:fontSize',
    'update:fontFamily',
    'update:padding',
    'update:fileName',
    'format',
    'copy:start',
    'copy:success',
    'copy:error',
  ],
  data() {
    return {
      selectedTheme: this.theme,
      selectedLanguage: this.language,
      selectedColor: this.backgroundColor,
      selectedFontSize: this.fontSize.toString(),
      selectedFontFamily: this.fontFamily,
      paddingY: this.padding.y,
    }
  },
  computed: {},
  watch: {
    theme(newTheme: ThemeType) {
      this.selectedTheme = newTheme
    },
    language(newLanguage: LanguageType) {
      this.selectedLanguage = newLanguage
    },
    backgroundColor(newColor: string) {
      this.selectedColor = newColor
    },
    fontSize(newSize: number) {
      this.selectedFontSize = newSize.toString()
    },
    fontFamily(newFamily: string) {
      this.selectedFontFamily = newFamily
    },
    padding: {
      handler(newPadding: { x: number; y: number }) {
        this.paddingY = newPadding.y
      },
      deep: true,
    },
  },
  methods: {
    async handleFormat() {
      if (this.isFormatting) return
      this.$emit('format')
    },
    handleThemeChange(value: string) {
      this.selectedTheme = value as ThemeType
      this.$emit('update:theme', value as ThemeType)
    },
    handleLanguageChange(value: string) {
      this.selectedLanguage = value as LanguageType
      this.$emit('update:language', value as LanguageType)
    },
    handleFontSizeChange(value: number) {
      this.selectedFontSize = value.toString()
      this.$emit('update:fontSize', value)
    },
    handleColorChange() {
      this.$emit('update:backgroundColor', this.selectedColor)
    },
    handleColorUpdate(value: string) {
      this.selectedColor = value
      this.$emit('update:backgroundColor', value)
    },
    handlePaddingYChange(value: number) {
      this.paddingY = value
      this.$emit('update:padding', { x: this.padding.x, y: value })
    },

    handleFontFamilyChange(value?: string) {
      if (value) {
        this.selectedFontFamily = value
      }
      this.$emit('update:fontFamily', this.selectedFontFamily)
    },

    async handleCopy() {
      try {
        // 获取编辑器窗口元素，使用editor-wrapper替代window-parent-wrapper
        const editorWrapper = document.querySelector('.editor-wrapper') as HTMLElement
        if (!editorWrapper) {
          console.error('找不到编辑器窗口元素')
          return
        }

        // 显示加载状态
        this.$emit('copy:start')

        // 使用html2canvas将元素转换为画布
        const canvas = await html2canvas(editorWrapper, {
          scale: 2, // 使用2倍缩放以获得更清晰的图像
          useCORS: true, // 允许加载跨域图像
          backgroundColor: null, // 保持背景透明
          logging: false, // 关闭日志
        })

        // 将画布转换为Blob
        canvas.toBlob(async (blob) => {
          if (blob) {
            try {
              // 创建ClipboardItem并复制到剪贴板
              const data = [new ClipboardItem({ 'image/png': blob })]
              await navigator.clipboard.write(data)
              this.$emit('copy:success')
            } catch (error) {
              console.error('复制到剪贴板失败:', error)
              // 回退方案：提供下载功能
              this.fallbackCopyImage(canvas)
              this.$emit('copy:error', '无法直接复制到剪贴板，已提供图片下载')
            }
          }
        }, 'image/png')
      } catch (error) {
        console.error('生成图片失败:', error)
        this.$emit('copy:error', '生成图片失败')
      }
    },

    // 提供回退下载功能
    fallbackCopyImage(canvas: HTMLCanvasElement) {
      const link = document.createElement('a')
      link.download = 'code-snapshot.png'
      link.href = canvas.toDataURL('image/png')
      link.click()
    },
  },
})
</script>

<style scoped>
/* 工具栏基本样式 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 12px;
  border-bottom: 1px solid #e2e8f0;
  background-color: #f8fafc;
  color: #334155;
  position: relative;
  z-index: 20;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  flex-wrap: wrap;
  gap: 8px;
}

/* 暗色模式下的工具栏 */
.toolbar.dark-toolbar {
  background-color: #1e293b;
  border-bottom: 1px solid #2d3748;
  color: #f1f5f9;
}

.toolbar-left {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.toolbar-right {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.toolbar-group {
  display: flex;
  gap: 6px;
  align-items: center;
  flex-wrap: nowrap;
}

.toolbar-button {
  padding: 4px 10px;
  height: 28px;
  font-size: 13px;
  color: #334155;
  background-color: white;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  white-space: nowrap;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  gap: 4px;
}

.toolbar-button:hover:not(:disabled) {
  background-color: #f1f5f9;
  border-color: #cbd5e1;
}

.toolbar-button:active:not(:disabled) {
  background-color: #e2e8f0;
}

.toolbar-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.button-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #64748b;
}

.button-text {
  white-space: nowrap;
}

/* 暗色主题工具栏下的样式调整 */
.dark-toolbar .toolbar-button {
  background-color: #1e293b;
  border-color: #475569;
  color: #f1f5f9;
}

.dark-toolbar .toolbar-button:hover:not(:disabled) {
  background-color: #334155;
  border-color: #64748b;
}

.dark-toolbar .button-icon {
  color: #94a3b8;
}

/* 改进的响应式布局优化 */
@media (max-width: 950px) {
  .toolbar {
    justify-content: space-around;
  }

  .toolbar-left,
  .toolbar-right {
    width: 100%;
    justify-content: space-between;
  }
}

@media (max-width: 768px) {
  .toolbar-group {
    gap: 5px;
  }

  .theme-select,
  .language-select,
  .font-size-stepper-container,
  .font-family-select,
  .padding-stepper-container {
    width: auto;
  }

  .action-buttons {
    margin-left: auto;
  }

  .filename-input {
    width: 120px;
  }
}

@media (max-width: 600px) {
  .font-size-stepper-container,
  .padding-stepper-container {
    width: 120px;
  }

  .stepper-input {
    width: 90px;
  }

  .toolbar-button .button-text {
    display: none;
  }

  .toolbar-button {
    padding: 4px;
    width: 28px;
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .toolbar {
    padding: 6px 8px;
  }

  .toolbar-left,
  .toolbar-right,
  .toolbar-group {
    width: 100%;
    flex-wrap: wrap;
    justify-content: flex-start;
    gap: 4px;
  }

  .select-wrapper {
    flex: 1;
    min-width: 80px;
  }

  .filename-input {
    width: 100px;
  }
}

.filename-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.filename-input {
  font-size: 13px;
  padding: 4px 24px 4px 8px;
  border-radius: 4px;
  height: 28px;
  box-sizing: border-box;
  outline: none;
  transition: all 0.2s ease;
  background-color: white;
  border: 1px solid #e2e8f0;
  color: #334155;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  width: 140px;
}

.filename-input:hover {
  border-color: #cbd5e1;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.filename-input:focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
}

/* 文件名清除按钮样式 */
.clear-filename-button {
  position: absolute;
  right: 6px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  padding: 2px;
  cursor: pointer;
  color: #94a3b8;
  transition: color 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 2px;
}

.clear-filename-button:hover {
  color: #64748b;
  background-color: #f1f5f9;
}

/* 暗色主题下的文件名输入框样式 */
.dark-toolbar .filename-input {
  background-color: #1e293b;
  border-color: #475569;
  color: #f1f5f9;
}

.dark-toolbar .filename-input:hover {
  border-color: #64748b;
}

.dark-toolbar .filename-input:focus {
  border-color: #60a5fa;
  box-shadow: 0 0 0 2px rgba(96, 165, 250, 0.2);
}

.dark-toolbar .clear-filename-button {
  color: #64748b;
}

.dark-toolbar .clear-filename-button:hover {
  color: #94a3b8;
  background-color: #334155;
}
</style>
